<?php

namespace app\api\controller;


use app\api\BaseController;
use app\api\middleware\Auth;
use app\api\validate\UserValidate;
use app\load\loadServices\AdminServices;
use think\Exception;
use think\exception\ValidateException;

/**
 * 用户类
 */
class User extends BaseController
{

    /**
     * 免登录方法
     * 控制器中间件 [登录 不需要鉴权]
     * @var array
     */
    protected $middleware = [
        Auth::class => ['except' => ['login']]
    ];


    /**
     * 用户详情
     * @url  api/user/info
     * @return void
     */
    public function info()
    {
        try {
            $info = AdminServices::Admin()->info(['id' => JWT_UID], 'username,name,mobile,sex,nickname,thumb,did,position_id');
            $this->apiSuccess('请求成功', $info);
        } catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }

    /**
     * 用户修改
     * @url  api/user/info
     * @return void
     */
    public function save()
    {
        $input = input('post.');
        try {
            \validate(UserValidate::class)->scene('save')->check($input);
            AdminServices::Admin()->save([
                'id' => JWT_UID] ,
                [$input['key'] => $input['value']]);
            $this->apiSuccess('请求成功');
        } catch (ValidateException|Exception $e) {
            $this->apiError($e->getMessage());
        }
    }


    /**
     * @title 登录
     * @param  ['username' ,'password']
     * @url  api/user/login
     * @result {"code":1,"msg":"登录成功","time":1627374739,"data":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGkuZ291Z3VjbXMuY29tIiwiYXVkIjoiZ291Z3VjbXMiLCJpYXQiOjE2MjczNzQ3MzksImV4cCI6MTYyNzM3ODMzOSwidWlkIjoxfQ.gjYMtCIwKKY7AalFTlwB2ZVWULxiQpsGvrz5I5t2qTs"}}
     * @return void
     */
    public function login()
    {
        $param = input('post.');
        try {
            \validate(UserValidate::class)->scene('login')->check($param);

            $token = AdminServices::Admin()->login($param['username'], $param['password']);
            if (empty($token)) {
                throw new Exception('登录失败');
            }

            $this->apiSuccess('登录成功', ['token' => $token]);
        } catch (ValidateException|\Exception $e) {
            $this->apiError($e->getMessage());
        }
    }


}